package cc.booku.owlbox;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.AppUpdate.DownloadService;
import cc.booku.owlbox.AppUpdate.app_version_class;
import cc.booku.owlbox.CollectionStation_norm.CS_FileScannerActivity;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.FileOperations.ShareUtils;
import cc.booku.owlbox.OrdinaryBooks_norm.OB_FileScannerActivity;
import cc.booku.owlbox.OrdinaryVideo_norm.OV_FileScannerActivity;
import cc.booku.owlbox.NavigationDataPage.NavDataActivity;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.SearchPage.SearchActivity;
import cc.booku.owlbox.UserSettingsPage.MyselfActivity;
import cc.booku.owlbox.UserSettingsPage.UserActivity;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static cc.booku.owlbox.FileOperations.FileoOperations.fileIsExists;

public class MainoldActivity extends AppCompatActivity {

    private List<FileName_C> fileName_cList = new ArrayList<FileName_C>();

    private TextView Tv_sizedata, tv_qq, fromfileurl;
    private Toolbar Toolbar;
    private ListView list_filename;
    private LinearLayout iv_user, lv_video, ll_nofile, lv_car;
    MyReceiver receiver = new MyReceiver();
    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator;
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";
    private TDialog tDialog;
    private static final int WHAT_LOADING = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainold);

//        Intent intent = new Intent(MainoldActivity.this, InitPage.class);
//        startActivity(intent);


        //创建文件并写入数据----生成案例
        //wtest();
        //读取符合规范的文件名，并且显示在listview
        try {
            //申请SD卡读写的权限
            FileoOperations.verifyStoragePermissions(MainoldActivity.this);
            //创建文件夹
            FileoOperations.makeRootDirectory(filePath);
            ReadDisplayDir(filePath);
        } catch (Exception e) {
            Toast.makeText(MainoldActivity.this, "读取文件目录失败" + "\n" + "如果您拒绝了存储权限请卸载重新安装", Toast.LENGTH_SHORT).show();
//异常处理
        }

        fromfileurl = (TextView) findViewById(R.id.fromfileurl);
        fromfileurl.setText(filePath);
        //提示重置配置文件
        //ProfileUpdate();
        //加载控件
        LoadControl();
        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        GetSize();

        //从qq微信引入文件
        getfile();

        //重新绘制menu
        invalidateOptionsMenu(); //重新绘制menu

        //软件版本自动检查
        softwareUpgrade();


        //初始化底部列表

        bottomlist();

        //初始化热门资源
        //Popular();

        // Log.d("initphone", "initphone----" + DataReport.initPhone(this));


        //检测服务器是否在线
//        Message msg = new Message();
//        msg.what = 14;
//        handler.sendMessage(msg);//用activity中的handler发送消息

        // Yukioa();
    }


    private void judgePermission(String FileUrl, String filename) {
        /**
         * 先检查权限是否打开，打开了就可以直接访问，未打开则先申请一波权限
         */
        if (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                makeAnExtraRequest();
            }
        } else {
            File f = new File(FileUrl);
            ShareUtils.shareWechatFriend(MainoldActivity.this, f, filename);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void makeAnExtraRequest() {
        int code = 100;
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        for (String string : permissions) {
            if (this.checkSelfPermission(string) != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(permissions, code);
                code++;
                return;
            }
        }
    }


    //csdn有个妹子问的问题
//想问一下从左至右显示“12345678”，接着显示“23456781”，
// 在接着显示“34567812”，一直到“81234567”，
// 然后返回“12345678”，这个代码怎么写？

    private void Yukioa() {

        /*
         * 初始化P_num=12345678
         * 循环给P_num+11111111
         * 比如第二个就是 2345678 9
         * 第三个就是     345678 90
         *
         * 可以看出来前面的吻合了，主要就是处理9这个数字了，要在数字为9的时候变为1
         * */
        //初始化 12345678 也就是一开始显示的数字
        int P_num = 12345678;
        //P_num+11111111
        for (int i = 0; i < 8; i++) {
            P_num = P_num + 11111111;
            //强制类型转换int转String把9替换成1
            String S_num = String.valueOf(P_num).replace("9", "1");
            //再把转换好的string赋值给P_num
            P_num = Integer.parseInt(S_num);
            //下面这个是输出用的
            Log.e("P_num---", "P_num===" + P_num);
        }


 /*下面这个是输出结果，c用同样的方式应该也可以实现

E/P_num---: P_num===23456781
E/P_num---: P_num===34567812
E/P_num---: P_num===45678123
E/P_num---: P_num===56781234
E/P_num---: P_num===67812345
E/P_num---: P_num===78123456
E/P_num---: P_num===81234567
E/P_num---: P_num===12345678

*/

    }


    private void Popular() {

        //,"离线热门资源":"yes"
        //读取文件
        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("离线热门资源");
            if (result.equals("yes")) {
                //如果文件存在就不遍历
                FileoOperations.copyFilesFromAssets(this, "Popular", filePath);
            }
        } catch (Exception e) {

//异常处理
        }


    }


    private void bottomlist() {

        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("加密敏感资源");
            if (result.equals("yes")) {
                //锁
                lv_car.setVisibility(View.GONE);
            } else {
                //锁
                lv_car.setVisibility(View.VISIBLE);

            }
        } catch (Exception e) {

            Toast.makeText(MainoldActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
//异常处理
        }

    }

    //弃用
    private void ProfileUpdate() {


        String Profile_A = FileoOperations.readAssetsTxt(this, "TxtData/Profile");
        String Profile_SD = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject objsd = JSONObject.parseObject(Profile_SD);
            String result_sd = objsd.getString("配置文件版本");
            String profileupdate = objsd.getString("配置文件校验");
            JSONObject obja = JSONObject.parseObject(Profile_A);
            String result_a = obja.getString("配置文件版本");
            if (profileupdate.equals("yes")) {

                if (Integer.parseInt(result_sd) < Integer.parseInt(result_a)) {
                    //提示配置文件有更新
                    //是否重建
                    DialogProfileuUP();
                }

            } else {
                Log.e("Profile配置---", "不需要检查配置文件版本");
            }

        } catch (Exception e) {

            Toast.makeText(MainoldActivity.this, "配置文件已经更新", Toast.LENGTH_SHORT).show();
            //不包含---重建配置文件
            FileoOperations.deleteFile(MainoldActivity.this, ProfilePath);
            FileoOperations.writeData(filePath, "Profile", FileoOperations.readAssetsTxt(this, "TxtData/Profile"));
//异常处理
        }

    }


    /**
     * 获取存储路径，自定义目录
     *
     * @return
     */
    public String getPath() {
        String state = Environment.getExternalStorageState();
        String path;
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            path = Environment.getExternalStorageDirectory().getPath()
                    + File.separator
                    + "CHINARES_UT"
                    + File.separator;
        } else {
            path = getCacheDir().getPath() + File.separator + "CHINARES_UT" + File.separator;
//CHINARES_UT:保存文件和照片的目录
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }


    private void shareTXT(String filename) {
        final Uri uri;
        final File file = new File(getPath() + filename);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= 24) {//若SDK大于等于24  获取uri采用共享文件模式
            uri = FileProvider.getUriForFile(this.getApplicationContext(), "cc.booku.owlbox.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }


        Intent share = new Intent(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setType(/*"application/pdf"*/getMimeType(file.getAbsolutePath()));//此处可发送多种文件
        share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        share.addCategory(Intent.CATEGORY_DEFAULT);
        share.setPackage("com.tencent.mobileqq");

//若需要分享到微信，只需要更改Package即可
//share.setPackage("com.tencent.mm")
        if (share.resolveActivity(MainoldActivity.this.getPackageManager()) != null) {
            MainoldActivity.this.startActivity(share);
        } else {
            Toast.makeText(MainoldActivity.this, "没有可以处理该文件的应用", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 根据文件后缀获取文件MIME类型
     *
     * @param filePath
     * @return
     */
    private static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "*/*";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }


    private void softwareUpgrade() {
//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//        JSONObject obj = JSONObject.parseObject(ProfileStr);
//        String result = obj.getString("软件版本检查");
//        if (result.equals("yes")) {

        //动态申请权限
        requestPermission();
        //注册广播
        regist();
        //得到程序最新版本地址

        //读取配置文件信息
        try {


            String ConfigFiles_json = FileoOperations.readAssetsTxt(MainoldActivity.this, "TxtData/ConfigFiles");
            JSONObject objsd = JSONObject.parseObject(ConfigFiles_json);
            String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
            String DecryptionAddress = Decrypt.RsaDecrypt(MainoldActivity.this, ciphertext);
            String appupdate = objsd.getString("APPUPDATE");

            AppVersion(DecryptionAddress + appupdate);

        } catch (Exception e) {

            Toast.makeText(MainoldActivity.this, "更新地址解析错误", Toast.LENGTH_SHORT).show();
//异常处理
        }


//
//
//
//
//
//
//
//
//
//
//
//        //读取文件
//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//        //读取配置文件信息
//        try {
//            JSONObject obj = JSONObject.parseObject(ProfileStr);
//            String result = obj.getString("软件版本检查");
//
//
//
//
//
//            String result2 = obj.getString("软件更新地址");
//            String ciphertext = obj.getString("地址密文");
//            String res = Decrypt.RsaDecrypt(MainoldActivity.this, ciphertext);
//
//          //  try {
//
//                //if (checkUrl(res, 400)) {
//                    //请求，将数据写入
//                    if (result.equals("yes")) {
//
//                        //动态申请权限
//                        requestPermission();
//                        //注册广播
//                        regist();
//                        //得到程序最新版本地址
//
//                        //读取配置文件信息
//                        try {
//
//                            AppVersion(res + result2);
//
//                        } catch (Exception e) {
//
//                            Toast.makeText(MainoldActivity.this, "更新地址解析错误", Toast.LENGTH_SHORT).show();
////异常处理
//                        }
//
//                    }
//               // } else Log.i("response===========>", res);
//
//            //} catch (Exception e) {
//
//               // Log.i("response===========>", res);
////异常处理
//           // }
//
//
//        } catch (Exception e) {
//
//            Toast.makeText(MainoldActivity.this, "更新地址解析错误", Toast.LENGTH_SHORT).show();
////异常处理
//        }


    }

    private void getfile() {
        Intent intent = getIntent();

        Uri uri = intent.getData();

        if (uri != null) {

//            String scheme= uri.getScheme();
//            String host=uri.getHost();
//            String port=uri.getPort()+"";
//            String path=uri.getPath();
//            String query=uri.getQuery();


            String path = uri.getPath();
            String host = uri.getHost();
            //处理字符串：//weixing
            if (path.indexOf("external/") != -1) {
                String newpath = path.replace("external/", "storage/emulated/0/");

                //显示弹窗是否需要复制文件到本地目录
                addfileDialog(newpath);
            }
            //qq/tim
            else if (path.indexOf("external_files/") != -1) {
                String newpath = path.replace("external_files/", "");

                //显示弹窗是否需要复制文件到本地目录
                addfileDialog(newpath);

            } else {
                Toast.makeText(MainoldActivity.this, "未适配路径：" + path, Toast.LENGTH_SHORT).show();

            }

            //判断文件是否符合条件


            //Toast.makeText(MainoldActivity.this, "scheme:"+scheme+"\nhost:"+host+"\nport:"+port+"\npath:"+path+"\nquery:"+query, Toast.LENGTH_SHORT).show();

        }
    }

    private void wtest() {
        //判断是否存在配置文件
//        if (!FileoOperations.fileIsExists(filePath + "DefaultPort" + ".txt")) {
//            //不存在就使用默认数据配置trim去除两端空格
//            FileoOperations.writeData(filePath, "DefaultPort", FileoOperations.readAssetsTxt(this, "TxtData/DefaultPort").replaceAll(" ", ""));
//
//        }
        //判断是否存在配置文件
        if (!fileIsExists(filePath + "Profile" + ".txt")) {
            //不存在就使用默认数据配置
            FileoOperations.writeData(filePath, "Profile", FileoOperations.readAssetsTxt(this, "TxtData/Profile"));

        } else {
            String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
            //读取配置文件信息
            try {
                JSONObject obj = JSONObject.parseObject(ProfileStr);
                String result = obj.getString("是否需要案例");
                if (result.equals("yes")) {

                    if (!fileIsExists(filePath + "案例视频_OrdinaryVideo_预告片_20200517" + ".txt")) {

                        FileoOperations.writeData(filePath, "案例视频_OrdinaryVideo_预告片_20200517", FileoOperations.readAssetsTxt(this, "TxtData/OrdinaryVideo"));

                    }
                    if (!fileIsExists(filePath + "案例文本_OrdinaryBooks_文章_20200517" + ".txt")) {

                        FileoOperations.writeData(filePath, "案例文本_OrdinaryBooks_文章_20200517", FileoOperations.readAssetsTxt(this, "TxtData/OrdinaryBooks"));

                    }
                    if (!fileIsExists(filePath + "采集站案例_CollectionStation_影视_20200517" + ".txt")) {

                        FileoOperations.writeData(filePath, "采集站案例_CollectionStation_影视_20200517", FileoOperations.readAssetsTxt(this, "TxtData/CollectionStation"));

                    }
                } else if (result.equals("no")) {
                    Log.e("Profile配置---", "不需要案例文件");
                }
            } catch (Exception e) {

                Toast.makeText(MainoldActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
//异常处理
            }


        }


//        String str = "大地云视频_erotic_情色_20200516.txt";
//        String[] str1 = str.split("\\.");
//        String[] strs = str1[0].split("_");
//        String owlTitle = strs[0];//文件标题
//        String owlNorm  = strs[1];//解析规范
//        String owlType = strs[2];//文件类型
//        String owlTime = strs[3];//更新时间

        //必须要的参数
        /**
         * 标题
         * 机制规范
         *   书籍
         *   影视
         *   图片
         *   连续剧
         * 数据类型（书籍，影视，电台）
         * 截至更新日期
         *
         * 例如：猫头鹰官方_film_视频_20200516.txt
         *       猫头鹰官方_sitcom_连续剧_20200516.txt
         *       猫头鹰官方_books_书籍_20200516.txt
         *
         *       大地云视频_erotic_情色_20200516.txt
         *       1.更新时间，2.标题名称，3.视频地址，4.id
         * */
    }

    public FileName_A fileName_a;
    public FileName_C fileName_c;

    private void ReadDisplayDir(String DirPath) {

        Log.e("111", "path" + DirPath);
        ArrayList<String> ss = FileoOperations.getFileName(DirPath, ".txt");
        for (String s : ss) {
            //大地云视频_erotic_情色_20200516.txt
            Log.e("111", "result:" + getCount(s, "_"));
            fileName_c = new FileName_C();
//            //String str = "大地云视频_erotic_情色_20200516.txt";
            String[] str1 = s.split("\\.");

            if (3 == getCount(str1[0], "_")) {
                String[] strs = str1[0].split("_");

                String owlTitle = strs[0];//文件标题
                String owlNorm = strs[1];//解析规范
                String owlType = strs[2];//文件类型
                String owlTime = strs[3];//更新时间


                Log.e("111", "owlTitle:" + owlTitle + "-----owlNorm:" + owlNorm + "-----owlType:" + owlType + "----owlTime:" + owlTime);

                fileName_c.setOwlTitle(owlTitle);//发送到实体类
                fileName_c.setOwlNorm(owlNorm);
                fileName_c.setOwlType(owlType);
                fileName_c.setOwlTime(owlTime);//添加到对象集合中
                fileName_cList.add(fileName_c);
            } else continue;

        }
        Message msg = new Message();
        msg.what = 9;
        handler.sendMessage(msg);//用activity中的handler发送消息

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 9:
                    ClickFileName((ArrayList<FileName_C>) fileName_cList);

                    Refresh();
                    break;

                case 14:

                    String ProfileStr = FileoOperations.readFromSDFile(MainoldActivity.this, ProfilePath);
                    //读取配置文件信息

                    JSONObject obj = JSONObject.parseObject(ProfileStr);

                    String result = obj.getString("检测服务器状态");
                    String testfile = obj.getString("测试地址");
                    String ciphertext = obj.getString("地址密文");

                    if (ciphertext.indexOf("maotouying:") != -1) {
                        String ciphertext2[] = ciphertext.split("maotouying:");
                        String res = Decrypt.RsaDecrypt(MainoldActivity.this, ciphertext2[1]);
                        testUrl(res + testfile, result);
                    } else if (ciphertext.indexOf("http") != -1) {
                        String res = ciphertext;
                        testUrl(res + testfile, result);
                    } else {

                        String res = Decrypt.RsaDecrypt(MainoldActivity.this, ciphertext);
                        testUrl(res + testfile, result);
                    }


                    break;


                case WHAT_LOADING:
                    if (tDialog != null) {
                        tDialog.dismiss();
                    }
                    return;
            }
        }
    };


    private void testUrl(String res, String result) {
        if (result.equals("yes")) {
            try {
                HttpResponse(res);

            } catch (Exception e) {

                Log.i("response===========>", res);
//异常处理
            }


//        if(checkUrl(res,400)) {
//            Log.d("serverTest", "serverTest----" + "链接成功");
//        }else  ServerStatusDialog();


        } else {
            Log.d("serverTest", "serverTest----" + "不检测服务器状态");
            //Toast.makeText(MainoldActivity.this, "不检测服务器状态1", Toast.LENGTH_SHORT).show();
        }


//    try {
//
//
//            //请求，将数据写入
//
////                Log.d("serverTest", res+testfile);
//////                        if (NetPingManager.ping(res)) {
//////                            Log.d("serverTest", "serverTest----" + "服务器在线");
//////                        } else {
//////                            ServerStatusDialog();
//////                        }
////                HttpResponse(res+testfile);
//
//
//
//
//
//
//    } catch (Exception e) {
//
//        Log.i("response===========>", res);
////异常处理
//    }
    }


    private void HttpResponse(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);
                if (res.equals("owl")) {

                    Log.i("response===========>", res);
                } else {
                    Log.i("response===========>", res);
                    ServerStatusDialog();
                }

            }
        });

    }


    public int getCount(String str, String key) {
        if (str == null || key == null || "".equals(str.trim()) || "".equals(key.trim())) {
            return 0;
        }
        int count = 0;
        int index = 0;
        while ((index = str.indexOf(key, index)) != -1) {
            index = index + key.length();
            count++;
        }
        return count;
    }


    public void ClickFileName(ArrayList<FileName_C> fileName_cList) {


        fileName_a = new FileName_A(R.layout.filename_item, MainoldActivity.this, fileName_cList);


        list_filename.setAdapter(fileName_a);
        //点按操作

        list_filename.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                // owlTitle,owlNorm,owlType,owlTime;
                final TextView owlTitle = (TextView) view.findViewById(R.id.owlTitle);
                final TextView owlNorm = (TextView) view.findViewById(R.id.owlNorm);

                final TextView owlType = (TextView) view.findViewById(R.id.owlType);
                final TextView owlTime = (TextView) view.findViewById(R.id.owlTime);


                String OwlTitle = owlTitle.getText().toString();
                String OwlNorm = owlNorm.getText().toString();
                String OwlType = owlType.getText().toString();
                String OwlTime = owlTime.getText().toString();

                //指定文件链接
                String specifiedFile = filePath + OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt";

                /*
                 *
                 * 普通视频：OrdinaryVideo_C
                 * 普通书籍:OrdinaryBooks
                 *
                 * */


                if ("OrdinaryVideo".equals(OwlNorm)) {

                    //跳转到FileScannerActivity打开指定文件
                    Intent intent = new Intent(MainoldActivity.this, OV_FileScannerActivity.class);

                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为specifiedFile
                    bundle.putString("SpecifiedFile", specifiedFile);
                    intent.putExtras(bundle);

                    startActivity(intent);


                } else if ("OrdinaryBooks".equals(OwlNorm)) {

                    //跳转到FileScannerActivity打开指定文件
                    Intent intent = new Intent(MainoldActivity.this, OB_FileScannerActivity.class);

                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为specifiedFile
                    bundle.putString("SpecifiedFile", specifiedFile);
                    intent.putExtras(bundle);

                    startActivity(intent);

                } else if ("CollectionStation".equals(OwlNorm)) {

                    //跳转到FileScannerActivity打开指定文件
                    Intent intent = new Intent(MainoldActivity.this, CS_FileScannerActivity.class);

                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为specifiedFile
                    bundle.putString("SpecifiedFile", specifiedFile);
                    intent.putExtras(bundle);

                    startActivity(intent);

                } else {

                    Toast.makeText(MainoldActivity.this, "请修改数据规范", Toast.LENGTH_SHORT).show();
                }


            }
        });

        //长按操作
        list_filename.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, final View view,
                                           final int i, long l) {


                final TextView owlTitle = (TextView) view.findViewById(R.id.owlTitle);
                final TextView owlNorm = (TextView) view.findViewById(R.id.owlNorm);

                final TextView owlType = (TextView) view.findViewById(R.id.owlType);
                final TextView owlTime = (TextView) view.findViewById(R.id.owlTime);


                String OwlTitle = owlTitle.getText().toString();
                String OwlNorm = owlNorm.getText().toString();
                String OwlType = owlType.getText().toString();
                String OwlTime = owlTime.getText().toString();

                //指定文件链接
                String FileUrl = filePath + OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt";
                DialogFilechanges(FileUrl, OwlTitle + "_" + OwlNorm + "_" + OwlType + "_" + OwlTime + ".txt");

                return true;     // 这里一定要改为true，代表长按自己消费掉了，若为false，触发长按事件的同时，还会触发点击事件</span></strong>
            }
        });


    }


    private void DialogFilechanges(final String FileUrl, String Filename) {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_longduration)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .addOnClickListener(R.id.tv_blank, R.id.tv_delete, R.id.tv_rename, R.id.tv_share, R.id.tv_share_qq)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        switch (view.getId()) {
                            case R.id.tv_share_qq:
                                if (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                                        PackageManager.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        makeAnExtraRequest();
                                    }
                                } else {
                                    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename);
                                    ShareUtils.shareQQFriend(MainoldActivity.this, f, Filename);
                                }

                                break;

                            case R.id.tv_share:

                                // 将上面获取到的imageUri再一次进行转化， 把他变成系统可以识别的Uri
                                if (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                                        PackageManager.PERMISSION_GRANTED || (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        makeAnExtraRequest();
                                    }
                                } else {
                                    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename);
                                    ShareUtils.shareWechatFriend(MainoldActivity.this, f, Filename);
                                }

                                // Log.d("temp7777", "temp：" + Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename);
                                //   judgePermission(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + Filename,Filename);

                                //shareTXT(Environment.getExternalStorageDirectory() + File.separator + "temp" + File.separator + Filename);
//                                String fileName = Environment.getExternalStorageDirectory() + File.separator + "temp" + File.separator + Filename;
//                                Intent shareIntent = new Intent(Intent.ACTION_SEND);
//                                //Android7.0版本以上使用FileProvider
//                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                                    shareIntent.putExtra(Intent.EXTRA_STREAM,
//                                            FileProvider.getUriForFile(MainoldActivity.this,
//                                                    "cc.booku.owlbox"
//                                                            + ".provider", new File(fileName)));
//                                }else {
//                                    shareIntent.putExtra(Intent.EXTRA_STREAM, new File(fileName));
//                                }
//                                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                                shareIntent.setType("*/*");//此处可发送多种文件
//                                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//这一句一定得写
//                                startActivity(Intent.createChooser(shareIntent, "分享文件"));


                                tDialog.dismiss();
                                break;
                            case R.id.tv_blank:
                                //对文件重命名，添加“不显示_”
                                //修改1路径就可以
                                String blankurl = FileUrl.replace("OwlDatabase/", "OwlDatabase/不显示_");
                                FileoOperations.renameFile(FileUrl, blankurl);
                                tDialog.dismiss();
                                break;
                            case R.id.tv_delete:
                                FileoOperations.deleteFile(MainoldActivity.this, FileUrl);

                                tDialog.dismiss();
                                break;
                            case R.id.tv_rename:

                                String Str[] = FileUrl.split("OwlDatabase/");
                                DialogRename(Str[1]);
                                tDialog.dismiss();
                                break;

                        }
                        //更新listview
                        fileName_cList.clear();
                        ReadDisplayDir(filePath);

                    }
                })

                .create()
                .show();
    }


    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }


    private void addfileDialog(final String newpath) {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_addfile)
                .setScreenWidthAspect(this, 0.9f)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.tv_filepath, newpath);
                    }
                })
                .addOnClickListener(R.id.tv_cancel, R.id.tv_confirm)
//                .setDialogAnimationRes(R.style.animate_dialog_scale)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        TextView Tv_filepath = viewHolder.getView(R.id.tv_filepath);
                        String pathcontent = Tv_filepath.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.tv_confirm:
                                FileoOperations.copyFile(pathcontent, filePath + pathcontent.substring(pathcontent.lastIndexOf("/") + 1));
                                Toast.makeText(MainoldActivity.this, "添加完成", Toast.LENGTH_SHORT).show();
                                fileName_cList.clear();
                                ReadDisplayDir(filePath);
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    private void DialogRename(final String Filename) {


        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_rename)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.editText, Filename);
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {


                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:
                                //String blankurl = content.replace("OwlDatabase/不显示_","OwlDatabase/");
                                FileoOperations.renameFile(filePath + Filename, filePath + content);
                                tDialog.dismiss();
                                break;

                        }


                    }
                })

                .create()
                .show();
    }


    /*
        static void setStatusBarColor(Activity activity, int statusColor) {
            Window window = activity.getWindow();
            //取消状态栏透明
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //添加Flag把状态栏设为可绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(statusColor);
            //设置系统状态栏处于可见状态
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != nulldata) {
                ViewCompat.setFitsSystemWindows(mChildView, false);
                ViewCompat.requestApplyInsets(mChildView);
            }
        }
    */
    private void LoadControl() {
        lv_car = (LinearLayout) findViewById(R.id.lv_car);
        lv_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainoldActivity.this, cc.booku.owlbox.UnNavDataPage.NavDataActivity.class);
                startActivity(intent);
            }
        });
        Tv_sizedata = (TextView) findViewById(R.id.sizedata);
        list_filename = (ListView) findViewById(R.id.list_filename);
        tv_qq = (TextView) findViewById(R.id.tv_qq);
        tv_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    SystemUtil.joinQQGroup(MainoldActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                } catch (Exception e) {
                    //异常处理
                    tv_qq.setText("打开失败！点击重试~");
                }
            }
        });
        ll_nofile = (LinearLayout) findViewById(R.id.ll_nofile);
        iv_user = (LinearLayout) findViewById(R.id.iv_user);
        iv_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出用户窗口
                //DialogMyself();
                Intent intent = new Intent();
                intent.setClass(MainoldActivity.this, MyselfActivity.class);
                startActivity(intent);
            }
        });


        lv_video = (LinearLayout) findViewById(R.id.lv_video);
        lv_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainoldActivity.this, NavDataActivity.class);
                startActivity(intent);
            }
        });

    }

    private void GetSize() {

//            WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//            DisplayMetrics dm = new DisplayMetrics();
//            wm.getDefaultDisplay().getMetrics(dm);
//            int width = dm.widthPixels;         // 屏幕宽度（像素）
//            int height = dm.heightPixels;       // 屏幕高度（像素）
//            float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//            int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//            // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
//            int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
//            int screenHeight = (int) (height / density);// 屏幕高度(dp)

        Tv_sizedata.setText("[刷新页面]");
        Tv_sizedata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {


                    try {

                        //刷新

                        fileName_cList.clear();
                        ReadDisplayDir(filePath);
                        invalidateOptionsMenu(); //重新绘制menu
                        bottomlist();//重新绘制底部列表
                        if (list_filename.getCount() == 0) {
                            ll_nofile.setVisibility(View.VISIBLE);
                            //Toast.makeText(MainoldActivity.this, "list_filename", Toast.LENGTH_SHORT).show();
                        } else if (list_filename.getCount() >= 1) {
                            list_filename.setVisibility(View.VISIBLE);

                        }

                        Tv_sizedata.setText("刷新成功");

                    } catch (Exception e) {

                        Tv_sizedata.setText("刷新失败");
//异常处理
                    }
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Tv_sizedata.setText("Ends justify the means");
                        }
                    }, 2000);
                } catch (Exception e) {
                    //异常处理
                    Tv_sizedata.setText("刷新失败");
                }

            }
        });
//        con_sizedata.setText("屏幕宽度（像素）：" + width+"\n" +
//                "屏幕高度（像素）：" + height+"\n" +
//                "屏幕密度（0.75 / 1.0 / 1.5）：" + density+"\n" +
//                "屏幕密度dpi（120 / 160 / 240）：" + densityDpi+"\n" +
//                "屏幕宽度（dp）：" + screenWidth+"\n" +
//                "屏幕高度（dp）：" + screenHeight);
        /*
            Log.d("h_bl", "屏幕宽度（像素）：" + width);
            Log.d("h_bl", "屏幕高度（像素）：" + height);
            Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
            Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
            Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
            Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);
*/

    }


    private void LoadToolbar() {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.inflateMenu(R.menu.menu_main);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                Intent intent = new Intent(MainoldActivity.this, UserActivity.class);
                startActivity(intent);
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_search:
                        Intent intent = new Intent();
                        //公开搜索
                        intent.setClass(MainoldActivity.this, SearchActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.action_unsearch:
                        intent = new Intent();
                        //un搜索
                        intent.setClass(MainoldActivity.this, cc.booku.owlbox.UnSearchPage.SearchActivity.class);
                        startActivity(intent);
                        break;

                    case R.id.action_lock:
                        intent = new Intent();
                        intent.setClass(MainoldActivity.this, NavDataActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.action_unlock:
                        intent = new Intent();
                        intent.setClass(MainoldActivity.this, cc.booku.owlbox.UnNavDataPage.NavDataActivity.class);
                        startActivity(intent);
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {


        menu.findItem(R.id.action_lock).setVisible(true);
        menu.findItem(R.id.action_unlock).setVisible(false);

        //搜索
        menu.findItem(R.id.action_search).setVisible(true);
        menu.findItem(R.id.action_unsearch).setVisible(false);
//
//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//        //读取配置文件信息
//        try {
//            JSONObject obj = JSONObject.parseObject(ProfileStr);
//            String result = obj.getString("加密敏感资源");
//            if (result.equals("yes")) {
//                //锁
//                menu.findItem(R.id.action_lock).setVisible(true);
//                menu.findItem(R.id.action_unlock).setVisible(false);
//
//                //搜索
//                menu.findItem(R.id.action_search).setVisible(true);
//                menu.findItem(R.id.action_unsearch).setVisible(false);
//            } else {
//                //锁
//                menu.findItem(R.id.action_lock).setVisible(false);
//                menu.findItem(R.id.action_unlock).setVisible(true);
//                //搜索
//                menu.findItem(R.id.action_search).setVisible(false);
//                menu.findItem(R.id.action_unsearch).setVisible(true);
//
//            }
//        } catch (Exception e) {
//
//            Toast.makeText(MainoldActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
////异常处理
//        }
        return super.onPrepareOptionsMenu(menu);
    }

    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void DialogMyself() {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_myself)
                .setScreenWidthAspect(this, 0.8f)
                .setGravity(Gravity.CENTER)
                .addOnClickListener(R.id.tv_search, R.id.tv_favorites, R.id.tv_history, R.id.tv_videodownload)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        switch (view.getId()) {
                            case R.id.tv_search:

                                tDialog.dismiss();
                                break;
                            case R.id.tv_favorites:

                                tDialog.dismiss();
                                break;
                            case R.id.tv_history:


                                tDialog.dismiss();
                                break;
                            case R.id.tv_videodownload:


                                tDialog.dismiss();
                                break;

                        }
                        //更新listview
                        fileName_cList.clear();
                        ReadDisplayDir(filePath);

                    }
                })

                .create()
                .show();
    }


    //********************************程序更新******************************
    //动态申请权限

    //动态申请权限
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(MainoldActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainoldActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    //注册广播
    private void regist() {
        IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }


    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-release.apk");
            //获取权限
            try {
                Runtime.getRuntime().exec("chmod 777" + file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent = new Intent(Intent.ACTION_VIEW);
            //如果设置，这个活动将成为这个历史堆栈上的新任务的开始
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //判读版本是否在7.0以上
            if (Build.VERSION.SDK_INT >= 24) {
                //7.0以上的版本
                Uri apkUri = FileProvider.getUriForFile(context, "cc.booku.owlbox.FileProvider", file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                //7.0以下的版本
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }
    }


    private void AppVersion(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                Log.i("response===========>", res);

                // Mtoast30(res);

                try {
                    initUpdate(res);
                } catch (Exception e) {

                    Log.i("response===========>", res);
//异常处理
                }


            }
        });

    }

    private String profileversion() {

        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("配置文件版本");
            return result;
        } catch (Exception e) {
            Log.e("--Method--", "读取失败");
        }
        return null;
    }

    private void initUpdate(String json) {


        //http://www.shuchuwenku.vip/MavBox/statistics/version.php
        List<app_version_class> list = JSON.parseArray(json, app_version_class.class);

        for (int i = 0; i < list.size(); i++) {
            String version = list.get(i).getVersion();
            String title = list.get(i).getTitle();
            String time = list.get(i).getTime();
            String content = list.get(i).getContent();
            String down_url = list.get(i).getDown_url();
            Log.i("response===jing====>", version + title + time + content + down_url);
            if (pm(list.get(i).getVersion())) {

                Tupdate(down_url, title, version, content);

            }


        }


    }

    private void Tupdate(final String down_url, final String title, final String filename, final String content) {


        if (fileIsExists(Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator + "app-release.apk")) {
            deleteSingleFile(Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator + "app-release.apk");
        }


        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_version_upgrde)
                .setScreenWidthAspect(this, 0.9f)
                .addOnClickListener(R.id.tv_cancel, R.id.tv_confirm)

                .setOnBindViewListener(new OnBindViewListener() {
                    public void bindView(BindViewHolder viewHolder) {
                        viewHolder.setText(R.id.tv_upgrade_content, content);
                    }
                })
                .setOnViewClickListener(new OnViewClickListener() {


                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.tv_confirm:

                                Toast.makeText(MainoldActivity.this, "如果没有弹出安装界面,请手动安装", Toast.LENGTH_SHORT).show();
                                Intent serviceIntent = new Intent(MainoldActivity.this, DownloadService.class);
                                serviceIntent.setData(Uri.parse(down_url));
                                startService(serviceIntent);


                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();

    }


    private boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                Toast.makeText(getApplicationContext(), "删除单个文件" + filePath$Name + "失败！", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            Toast.makeText(getApplicationContext(), "删除单个文件失败：" + filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private boolean pm(String versioncode) {

        //获取包管理者对象
        PackageManager pm = getPackageManager();

        PackageInfo info = null;
        try {
            info = pm.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //获取版本号和版本名称


        if (versioncode.equals(info.versionName)) {
            return false;
        } else return true;


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }


    private void DialogProfileuUP() {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_upprofile)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.editText, FileoOperations.readAssetsTxt(MainoldActivity.this, "TxtData/Profile"));
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:
//
                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:

                                Toast.makeText(MainoldActivity.this, "配置文件已经更新", Toast.LENGTH_SHORT).show();
                                //不包含---重建配置文件
                                FileoOperations.deleteFile(MainoldActivity.this, ProfilePath);
                                FileoOperations.writeData(filePath, "Profile", content);

                                tDialog.dismiss();
                                break;

                        }


                    }
                })

                .create()
                .show();
    }


    private void Refresh() {
        try {


            if (list_filename.getCount() == 0) {
                ll_nofile.setVisibility(View.VISIBLE);
                //Toast.makeText(MainoldActivity.this, "list_filename", Toast.LENGTH_SHORT).show();
            } else if (list_filename.getCount() >= 1) {
                list_filename.setVisibility(View.VISIBLE);

            }


        } catch (Exception e) {
            Log.e("--Method--", "refresh失败");

//异常处理
        }
    }

    //****************************************************************服务器状态检测

    private void ServerStatusDialog() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_serverstatus)
                .setScreenWidthAspect(this, 0.9f)
                .setCancelableOutside(false)
                .addOnClickListener(R.id.tv_close, R.id.tv_qqgroup)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {

                            case R.id.tv_close:
                                tDialog.dismiss();
                                break;
                            case R.id.tv_qqgroup:
                                try {
                                    SystemUtil.joinQQGroup(MainoldActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                                } catch (Exception e) {
                                    //异常处理
                                    Log.e("--失败--", "添加失败");
                                }
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    //没有用
    public static Boolean checkUrl(String address, int waitMilliSecond) {
        try {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(waitMilliSecond);
            conn.setReadTimeout(waitMilliSecond);

            //HTTP connect
            try {
                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int code = conn.getResponseCode();
            if ((code >= 100) && (code < 400)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
